package cn.tedu.yxcar.product.service.impl;


import cn.tedu.yxcar.product.ex.CoolSharkServiceException;
import cn.tedu.yxcar.product.mapper.OrderMapper;

import cn.tedu.yxcar.product.pojo.dto.order.OrderAddDTO;
import cn.tedu.yxcar.product.pojo.entity.order.Order;
import cn.tedu.yxcar.product.pojo.entity.user.CsmallAuthenticationInfo;
import cn.tedu.yxcar.product.service.IOrderService;

import cn.tedu.yxcar.product.web.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServerImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void addOrder(OrderAddDTO orderAddDTO) {
        log.debug("开始处理【添加订单】的业务，参数：{}", orderAddDTO);
        // 创建Order对象
        Order order = new Order();
        // 调用BeanUtils.copyProperties(源,目标)将参数对象中的属性复制到Album对象中
        BeanUtils.copyProperties(orderAddDTO, order);
        // 调用Mapper对象的insert()执行插入相册数据
        log.debug("即将执行插入数据，参数：{}", order);
        int rows = orderMapper.insertOrder(order);
        if (rows != 1) {
            String message = "添加订单失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, message);
        }
    }

    public CsmallAuthenticationInfo getUserInfo(){
        // 获取SpringSecurity上下文对象
        UsernamePasswordAuthenticationToken token=
                (UsernamePasswordAuthenticationToken)
                        SecurityContextHolder.getContext().getAuthentication();
        // 为了程序逻辑严谨,判断一下token是否为null
        if(token == null){
            throw new CoolSharkServiceException(
                    ResponseCode.UNAUTHORIZED,"您还没有登录");
        }
        // 从SpringSecurity上下文对象中获取用户信息
        CsmallAuthenticationInfo userInfo=
                (CsmallAuthenticationInfo) token.getCredentials();
        // 最终返回用户信息
        return userInfo;
    }
    public Long getUserId(){
        return getUserInfo().getId();
    }
}
